import React, { useEffect, useState } from 'react'
import MyTabbar from '@c/MyTabbar'
import { useSelector, useDispatch } from 'umi'
import { Checkbox, Stepper, Button } from 'antd-mobile';
import './style.scss'
export default function index() {
  const dispatch = useDispatch();
  // 购物车中的数据
  const cartState = useSelector(state => state.cart);
  useEffect(() => {
    dispatch({
      type: 'cart/fetchCartInfo'
    })
  }, [])
  // 商品管理状态
  const [delState, setDelState] = useState(false);
  // 修改商品购买数量
  const changeItemNum = (key: string, number: number) => {
    dispatch({
      type: 'cart/changeItemNum',
      params: {
        key,
        number
      }
    })
  }
  // 修改商品选中状态
  const changeItemSelected = (key: string, selected: boolean) => {
    dispatch({
      type: 'cart/cartItemSelected',
      params: {
        key,
        selected
      }
    })

  }
  // 删除商品
  const  delItems = () => {
    // 得到已经选中的 商品key 存储到数组
    const selectedItemKeys:any = [];
    cartState.items.forEach(item => {
      if (item.selected) {
        selectedItemKeys.push(item.key)
      }
    })
    dispatch({
      type: 'cart/delItems',
      params: {
        key: selectedItemKeys.join(',')
      }
    })
  }
  return (
    <div>
      <div className="cart-container">
        <div className="cart-top">
          <div className="count">
            购买数量<span>{cartState.number}</span>
          </div>
          <div className="manager" onClick={
            () => {
              setDelState(!delState)
            }
          }>
            {
              delState
                ?
                '取消'
                :
                '管理'
            }
          </div>
        </div>
        <div className="items">
          {
            cartState.items.map(item => (
              <div className="item" key={item.id}>
                <Checkbox checked={item.selected} onChange={
                  (selected) => {
                    changeItemSelected(item.key, selected)
                  }
                } />
                <img src={item.pic} alt="" />
                <div className="item-info">
                  <h4>{item.name}</h4>
                  <p>价格￥{item.price}</p>
                  <Stepper min={1} value={item.number} onChange={
                    (value) => {
                      changeItemNum(item.key, value)
                    }
                  } />
                </div>
              </div>
            ))
          }

        </div>
      </div>
      {/* 提交订单栏 */}
      <div className="cart-submit">
        <div>
          全选：
          <Checkbox checked={cartState.allChecked} onChange={() => { }} />
        </div>
        <span>总价格：￥{cartState.price}</span>
        <Button color='danger'>提交</Button>
        {
          delState
          &&
          <Button onClick={
            () => {
              delItems()
            }
          }>删除</Button>
        }

      </div>
      <MyTabbar />
    </div>
  )
}
